//
//  PhotoAlertVC.swift
//  mmda
//
//  Created by 李陆涛 on 2018/8/14.
//  Copyright © 2018年 mmda. All rights reserved.
//

import UIKit
import HXPhotoPicker

enum SelectType {
    case photo
    case video
    case all
}

class PhotoAlertVC: UIViewController {
    
    private var type:SelectType = .all
    private var subtype:SelectType = .photo
    private var handel:(([HXPhotoModel],SelectType)->Void)?
    private var maxCount:Int = 9
    private var alertVC:UIAlertController?
    
    class func alert(type:SelectType,maxCount:Int,vc:UIViewController,handel:@escaping (([HXPhotoModel],SelectType)->Void)) {
        
        let alertVC = PhotoAlertVC()
        alertVC.alertVC = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
        
        alertVC.type = type
        
        alertVC.setupUI()
        alertVC.handel = handel
        alertVC.maxCount = maxCount
        
        alertVC.view.backgroundColor = UIColor.clear
        alertVC.modalPresentationStyle = .overCurrentContext
        
        vc.present(alertVC, animated: false, completion: nil)
        
        alertVC.present(alertVC.alertVC!, animated: true, completion: nil)
        
    }
    
    private func setupUI() {
        
        let cameraAction = UIAlertAction(title: "拍摄\n照片或视频", style: UIAlertActionStyle.default) { _ in
            
            self.cameraAction()
        }
        
        self.alertVC?.addAction(cameraAction)
        
        if type != .video {
            
            let libaryAction1 = UIAlertAction(title: "选择照片", style: UIAlertActionStyle.default) { _ in
                
                self.subtype = .photo
                self.photoLibaryAction()
            }
            
            self.alertVC?.addAction(libaryAction1)
        }
        
        if type != .photo {
            
            let libaryAction2 = UIAlertAction(title: "选择视频", style: UIAlertActionStyle.default) { _ in
                
                self.subtype = .video
                self.photoLibaryAction()
            }
            
            self.alertVC?.addAction(libaryAction2)
        }
        
        
        self.alertVC?.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: { _ in
            
            self.dismiss(animated: true, completion: nil)
        }))
        
        
    }
    
    //    override func viewDidAppear(_ animated: Bool) {
    //
    //        super.viewDidAppear(animated)
    //
    //
    //    }
    
    
    private func cameraAction() {
        
        let cameraVC = LLTCustomCamera()
        
        cameraVC.selectType = self.type
        
        self.present(cameraVC, animated: true, completion: nil)

        cameraVC.completeHander = {
            
            [weak self] image,url,suc in
            guard let `self` = self else { return }
            
            weak var cVC = cameraVC
            
            cVC?.dismiss(animated: false, completion: nil)
            
            if let url = url {
                
                let editVC = LLTVideoEdit(maxDuration: CGFloat(AppManager.share.appModel?.video_time ?? 15), vedio: url, phAsset:nil)
                
                editVC.completeHander = {
                    image,url,suc in
                    
                    self.closeAll()
                    
                    guard let url = url else {
                        self.handel?([],.video)
                        return
                    }
                    
                    if let model = HXPhotoModel(videoURL: url) {
                        
                        self.handel?([model],.video)
                    } else {
                        
                        self.handel?([],.video)
                    }
                    
                }
                
                self.present(editVC, animated: false, completion: nil)
                
                return
            }
            
            if let image = image {
                
                if let model = HXPhotoModel(image: image) {
                    
                    self.handel?([model],.photo)
                }
            }
            
            self.closeAll()
            
            return
            
        }
    }
    
    private func closeAll() {
        
        
        var rootVC = self.presentingViewController
        
        while ((rootVC?.presentingViewController) != nil) {
            
            rootVC = rootVC?.presentingViewController
        }
        
        rootVC?.dismiss(animated: false, completion: nil)
    }
  
    private func photoLibaryAction() {
        
        let browser = HXPhotoManager(type: self.subtype == .photo ? .photo:.video)
        
        browser?.configuration.openCamera = false
        browser?.configuration.selectTogether = false
        browser?.configuration.cameraCellShowPreview = false
        browser?.configuration.navBarBackgroudColor = UIColor.black
        browser?.configuration.hideOriginalBtn = true
        
        if subtype == .video {
            
            browser?.configuration.singleSelected = true
            browser?.configuration.singleJumpEdit = false
            browser?.configuration.videoCanEdit = true
            browser?.configuration.videoMaxDuration = 15
            browser?.configuration.replaceVideoEditViewController = true
            
            
            browser?.configuration.shouldUseVideoEdit = {
                
                [weak self] viewController,manager,beforeModel in
                guard let `self` = self else { return }
                
                guard let asset = beforeModel?.asset else {
                    
                    return
                }
                
                let editVC = LLTVideoEdit(maxDuration: 15, vedio: nil, phAsset:asset )
                
                editVC.completeHander = {

                    [weak self] image,url,success in
                    guard let `self` = self else { return }
 
                    if success {
                        
                        let afterModel = HXPhotoModel(videoURL: url)
                        
                        self.handel?([afterModel!],.video)
                        
                        self.closeAll()
                    }
                }
                viewController?.present(editVC, animated: true, completion: nil)
            }
            
        } else {
            
            browser?.configuration.photoMaxNum = maxCount
            browser?.configuration.deleteTemporaryPhoto = false
            browser?.configuration.lookLivePhoto = false
            browser?.configuration.lookGifPhoto = true
            browser?.configuration.saveSystemAblum = false
        }

        self.hx_presentAlbumListViewController(with: browser, done: {
            
            [weak self] allList, photoList, videoList, imageList, original, viewController in
            guard let `self` = self else { return }
            
            print("------------完成")
            
            if let list = allList {
                
                print("------------\(list.count)")
                
                if let model = list.first {

                    if model.subType == HXPhotoModelMediaSubTypeVideo {

                        
                        print("------------导出完成3");
                        model.thumbPhoto = model.tempImage

                        self.handel?([model],.video)

                        self.closeAll()
                        print("------------导出完成4");
                        return
                    }

                }
                
                self.handel?(list,self.subtype)
                
                self.closeAll()
                
            }
            
        }) {
            viewController in
            
            self.closeAll()
        }
        
    }
    
}


